//
//  LDYHomeTableViewController.swift
//  李东阳微博
//
//  Created by 李东阳 on 16/4/16.
//  Copyright © 2016年 李东阳. All rights reserved.
//

import UIKit

let cellIdentifier = "cellIdentifier"
class LDYHomeTableViewController: LDYVisitorTableViewController {

    var status:[LDYStatus] = [LDYStatus]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

     

        if !islogin{
        
           visitorView?.setVisitorInfo(nil , title: nil)
            
               return
        }
          setupUI()
        self.tableView.registerClass(LDYHomeCell.self, forCellReuseIdentifier: cellIdentifier)
        
        "TODO:|FIXME:  这是先设置的高度"
         self.tableView.rowHeight = UITableViewAutomaticDimension
        
         self.tableView.estimatedRowHeight = 300
        
        // 设置风格
        tableView.separatorStyle = .None
        
        //获取新浪微博的数据
         loadData(indicatorView.isAnimating())
        
        
        tableView.tableFooterView = indicatorView
     
          tableView.addSubview(refresh)
        refresh.addTarget(self, action: "refreshAction", forControlEvents: UIControlEvents.ValueChanged)

    }
    
    @objc private func refreshAction(){
        
    loadData(indicatorView.isAnimating())
    }
    
    func endActionWith(){
     indicatorView.stopAnimating()
    
    }
    
    
    //MARK: - 设置tableView 的footView

    private lazy var indicatorView: UIActivityIndicatorView = {
    
    let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
       view.color = myTintColor
        
      view.sizeToFit()
        return view
    }()
    private lazy var  refresh : LDYRefreshControl = LDYRefreshControl()
    
    //MARK: - 设置 视图showCountLabel
    private  func setupUI(){
    
    navigationController?.view.insertSubview(showCountLabel, aboveSubview: (navigationController?.navigationBar)!)
    showCountLabel.frame = CGRect(x: 0, y: 64 - 34, width: UIScreeonwidth, height: 34)
        
    }
    
    
    
    //MARK: - 显示得到多少数据label
    private lazy var showCountLabel: UILabel = {
    
    let lab = UILabel(textColor: UIColor.whiteColor(), textFont: 14)
        
        lab.textAlignment = .Center
        lab.backgroundColor = myTintColor
        lab.text = "显示微博条数文字"
        lab.hidden = true
           return lab
        
    }()

 
    
    func setcountLabelAnim(countWeibo: Int){
    
        showCountLabel.hidden = false
        var countString = ""
        
        if  countWeibo == 0 {
            
        countString = "您已经是最新的微博了"
        
        }else{
        countString = "您更新了\(countWeibo)条微博"
        
        }
    
    showCountLabel.text = countString
      
        UIView.animateWithDuration(1, animations: { () -> Void in
            
            self.showCountLabel.frame.origin.y = 64
            }) { (_) -> Void in
            self.showCountLabel.frame.origin.y = 64 - 34
                
                 self.showCountLabel.hidden = true
        }
        
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return status.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            //MARK: -  cell赋值
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! LDYHomeCell
        

        cell.status = status[indexPath.row]
        
        return cell
        
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
       
        //判断是否已经 滑动到底部
        if  indexPath.row == (status.count) - 1 && !indicatorView.isAnimating(){
            
              loadData(true)
        //设置动画
            indicatorView.startAnimating()
        
        }
    }
}

//MARK: - 请求微博首页数据

extension LDYHomeTableViewController {
    
    func loadData(isPullUp:Bool ){
        
        var sinceId : Int64 = 0
        var maxId: Int64 = 0
        
        if isPullUp{
        
            //MARK: - 上拉加载更多
            sinceId = 0
            
            maxId = status.last?.id ?? 0

            if maxId > 0 {
            
            maxId = maxId - 1
                
            }
            
        }else{
        
            //MARK: - 下拉刷新
          sinceId = status.first?.id ?? 0
            maxId = 0
            
            
        }
            
            
          LDYnetWorkTools.sharedTools.loadStatus(LDYUserAccountTools.userAccountTools.accessToken!, since_id: sinceId, max_id: maxId ){ (response, error) -> () in
            
              self.endRefreshing()
            if error != nil{
                
                print(error)
            }
            
            guard let array = response?["statuses"] as?[[String: AnyObject]] else{
                
                print("返回的不是一个数组")
                return
            }
            
            //MARK: - 创建临时数组
            var temArray:[LDYStatus] = [LDYStatus]()
            
            //MARK: -  遍历数组
            for dic in  array{
                
                let status = LDYStatus(dict: dic)
                
                temArray.append(status)
                
//                print(temArray.count)
                
            }
            
            if isPullUp{
                
             self.status = self.status + temArray
                
            }else{
            
            self.status =  temArray + self.status
                
                print(self.status.count)
                if self.showCountLabel.hidden == true{
                
                self.setcountLabelAnim(temArray.count)
                }
                
            }
            
           
            print(self.status.count)
            self.tableView.reloadData()
        
            
            }
            
        }
    
    // 停止动画方法
    func endRefreshing(){
        self.indicatorView.stopAnimating()
        self.refresh.endRefreshing()
    }
    
    
    
//    func deom(){

        
//        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
//        
//        
//        //MARK: -  请求参数
//        let parm = [
//            "access_token": LDYUserAccountTools.userAccountTools.accessToken!
//        ]
//        
//        LDYnetWorkTools.sharedTools.request(methedTools.GET, urlString: urlString, parm: parm ) { (response, error) -> () in
//            
//            if error != nil{
//                
//                print(error)
//            }
//            
//            guard let array = response?["statuses"] as?[[String: AnyObject]] else{
//                
//                print("返回的不是一个数组")
//                return
//            }
//            
//            //MARK: - 创建临时数组
//            var temArray:[LDYStatus] = [LDYStatus]()
//            
//            //MARK: -  遍历数组
//            for dic in  array{
//                
//                let status = LDYStatus(dict: dic)
//                
//                temArray.append(status)
//                
//                print(temArray.count)
//                
//            }
//            
//            self.status = temArray
//            
//            self.tableView.reloadData()
//    
//    }
    
         
    }
        


